package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.bean.UserInfo;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import java.lang.ref.WeakReference;
import com.lily.aidouzixun.util.MyConstant.*;
/**
 * 修改用户信息页面
 */
public class ModifyUserinfoActivity extends Activity {
    private static final String TAG = "ModifyUserinfoActivity";

    private TitleBar mTitleBar;
    private static ProgressDialog mProgressDialog; //网络请求时用的进度条
    private EditText etModify;
    private Button bnSave;

    private String key = "";
    private Activity mActivity;
    private static Context mContext;
    private String backTitle;   //返回标题
    private String title = "";
    private MyHandler myHandler;
    private UserInfo mUserInfo;
    /**
     * 修改标志位
     * 0-昵称
     * 1-电话手机号
     */
    private int action = -1; //用于标识修改类型  101-昵称
    private String modifyContent = "";  //修改的内容

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_modify_detail);
        init();
        findViews();
        setListeners();
    }

    /**
     * 初始化参数
     */
    private void init() {
        this.key += this.hashCode();
        mActivity = ModifyUserinfoActivity.this;
        mContext = ModifyUserinfoActivity.this;
        mUserInfo = MyConfig.getUserInfo(mContext);
        //得到返回标题
        Intent intent = getIntent();
        backTitle = intent.getStringExtra(MyConstant.IntentKey.BACK_TITLE);
        action = intent.getIntExtra(IntentKey.ACTION, -1);   //修改标志位
        title = intent.getStringExtra(IntentKey.TITLE);
        modifyContent = intent.getStringExtra(IntentKey.MODIFY_CONTENT);
        myHandler = new MyHandler(mActivity);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
    }
    /**
     * 找到控件
     */
    private void findViews() {
        //标题栏
        mTitleBar = (TitleBar) findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(title);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);

        etModify = (EditText) this.findViewById(R.id.et_modify);
        if (Validator.isEffective(modifyContent)) {
            etModify.setText(modifyContent);
            etModify.setSelection(modifyContent.length());
        }
        etModify.requestFocus();
        bnSave = (Button) this.findViewById(R.id.bn_save);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //保存信息
        bnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                modifyContent = etModify.getText().toString().trim();
                if (Validator.isEffective(modifyContent)) {
                    modify(modifyContent);
                }

            }
        });
    }

    /**
     *修改用户信息
     */
    private void modify(String modifyContent) {
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(RequireParams.MODIFY_USERINFO, modifyContent);
        param.put(MyConstant.RequireParams.ACTION, action);
        switch (action) {
            case ModifyAction.MODIFY_NICKNAME:  //修改昵称
                String nickname = mUserInfo.getNickname();
                if (Validator.isEffective(nickname)) {
                    if (nickname.equals(modifyContent)) {
                        T.shortToast(mContext, "昵称没有任何改变！");
                        return ;
                    }
                }
                break;
            case ModifyAction.MODIFY_PHONE: //修改手机号
                String phone = mUserInfo.getPhone();
                if (Validator.isEffective(phone)) {
                    if (phone.equals(modifyContent)) {
                        T.shortToast(mContext, "手机号没有任何改变！");
                        return ;
                    }
                }
                break;
            case ModifyAction.MODIFY_EMAIL: //邮箱
                String email = mUserInfo.getEmail();
                if (Validator.isEffective(email)) {
                    if (email.equals(modifyContent)) {
                        T.shortToast(mContext, "邮箱没有任何改变！");
                        return ;
                    }
                }
                break;
            default:
                break;
        }
        param.put(MyConstant.RequireParams.DATA_TYPE, DataType.MODIFY_USERINFO);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.MODIFY_USERINFO + action);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }
    /**
     * 修改信息完成
     */
    private void modifySuccess() {
        Intent intent = new Intent();
        intent.putExtra(IntentKey.MODIFY_CONTENT, modifyContent);
        switch (action) {
            case ModifyAction.MODIFY_NICKNAME:  //修改昵称
                setResult(IntentForResultCODE.MODIFY_NICKNAME_RESULTCODE, intent);
                mUserInfo = MyConfig.getUserInfo(mContext);
                mUserInfo.setNickname(etModify.getText().toString().trim());
                MyConfig.setUserInfo(mContext, mUserInfo);
                break;
            case ModifyAction.MODIFY_PHONE: //修改手机号
                setResult(IntentForResultCODE.MODIFY_PHONE_RESULTCODE, intent);
                mUserInfo = MyConfig.getUserInfo(mContext);
                mUserInfo.setPhone(etModify.getText().toString().trim());
                MyConfig.setUserInfo(mContext, mUserInfo);
                break;
            case ModifyAction.MODIFY_EMAIL: //邮箱
                setResult(IntentForResultCODE.MODIFY_EMAIL_RESULTCODE, intent);
                mUserInfo = MyConfig.getUserInfo(mContext);
                mUserInfo.setEmail(etModify.getText().toString().trim());
                MyConfig.setUserInfo(mContext, mUserInfo);
                break;
            default:
                break;
        }
        mActivity.finish();
    }
    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final ModifyUserinfoActivity activity = (ModifyUserinfoActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (mProgressDialog != null) {
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.MODIFY_USERINFO) {
                                SparseArray<Object> modifyResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) modifyResult.get(0);
                                if ("0".equals(errno)) {
                                    String message = (String) modifyResult.get(1);
                                    if (Validator.isEffective(message)) {
                                        T.longToast(mContext, message);
                                    } else {
                                        T.longToast(mContext, "修改成功！");
                                    }
                                    //修改成功
                                    activity.modifySuccess();
                                } else if("1".equals(errno)) {
                                    T.longToast(mContext, "修改失败！");
                                } else {
                                    T.longToast(mContext, "其他错误！");
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
}
